{% extends 'admin/base.html' %}

{% block title %}新增文章页{% endblock %}

{% block main_title %}新增文章{% endblock %}

{% block head %}
    <link rel="stylesheet" href="{{ url_for('static', filename='rich/toastui-editor.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='editor/prism.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='editor/toastui-editor-highlight.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='editor/toastui-editor-plugin-color-syntax.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='editor/tui-color-picker.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='editor/dark.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='rich/toastui-editor.min.css') }}">    <script src="{{ url_for('admin.static', filename='editor/latest/toastui-editor-all.min.js') }}"></script> x
    <script src="{{ url_for('static', filename='editor/zh-cn.js') }}"></script> x
    <script src="{{ url_for('static', filename='editor/toastui-editor-plugin-code-syntax-highlight-all.min.js') }}"></script>
    <script src="{{ url_for('static', filename='editor/tui-color-picker.min.js') }}"></script>
    <script src="{{ url_for('static', filename='editor/toastui-editor-plugin-color-syntax.min.js') }}"></script>
{% endblock %}

{% block content %}
    <form class="layui-form head_form" lay-filter="filter-test-layer">
        <div class="layui-row layui-col-space15" style="margin: 10px 20px;">
            <div class="layui-col-md9">
                <input type="text" name="title" lay-affix="clear" class="layui-input" placeholder="请输入文章标题">
            </div>
            <div class="layui-col-md1">
                <select name="category">
                    <option value="">选择分类</option>
                    {% for category in category_list %}
                        <option value="{{ category.id }}">{{ category.name }}</option>
                    {% endfor %}
                </select>
            </div>

            <div class="layui-col-md1">
                <button type="button" lay-submit lay-filter="saveDraft" class="layui-btn">保存草稿</button>
            </div>
            <div class="layui-col-md1">
                <button type="button" lay-on="test-page-custom" class="layui-btn layui-bg-blue">发布文章</button>
            </div>
        </div>
    </form>
    <div id="editor"></div>
    <script type="text/html" id="post-template">
        <form class="layui-form" style="margin: 16px;">
            <div class="layui-form-item">
                <label class="layui-form-label">标签(非必填)</label>
                <div class="layui-input-block">
                    {% for tag in tag_list %}
                        <input type="checkbox" name="{{ tag.id }}" title="{{ tag.name }}">
                    {% endfor %}
                </div>
            </div>

            <div style="display: flex;justify-content: flex-end; padding:0 30px 30px 0">
                <button type="button" lay-filter="publish" lay-submit class="layui-btn layui-bg-blue">发布文章</button>
            </div>
        </form>
    </script>

    <script src="{{ url_for('static', filename='js/activate-power-mode.js') }}"></script>
    <script>
        POWERMODE.colorful = true; // ture 为启用礼花特效
        POWERMODE.shake = false; // false 为禁用震动特效
        document.body.addEventListener('input', POWERMODE);
    </script>

{% endblock %}

{% block script %}
    <script>
        layui.use(function () {
            let $ = layui.$;
            let layer = layui.layer;
            let util = layui.util;
            let form = layui.form;
            let img_list = [];

            let plugin = toastui.Editor.plugin

            // 生成富文本编译器
            let editor = new toastui.Editor({
                el: document.querySelector('#editor'),
                initialEditType: 'markdown', // 初始编辑类型，这里是 Markdown
                previewStyle: 'vertical', // 预览样式，可以是 'tab', 'vertical'
                height: '700px', // 编辑器高度
                language: 'zh-CN',
                plugins: [plugin.codeSyntaxHighlight, plugin.colorSyntax],
                {#theme: 'dark',#}
                hooks: {
                    addImageBlobHook: (blob, callback) => {
                        uploadImage(blob, function (imageUrl) {
                            callback(imageUrl)
                        }, function (error) {
                            console.log('图片上传失败:', error)
                        })
                    }
                }
            });
           // 上传图片方法
            function uploadImage(imageBlob, successCallback, errorCallback) {
                let formData = new FormData()
                formData.append('file', imageBlob)
                formData.append('name', imageBlob.name === 'image.png' ? imageBlob.lastModified + '.png' : imageBlob.name)
                formData.append('size', imageBlob.size.toString())
                $.ajax({
                    url: '{{ url_for('admin.file_upload') }}',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if (data.url !== '') {
                            img_list.push(data)
                            successCallback(data.url)
                        }
                    },
                    error: function () {
                        errorCallback()
                    }
                })
            }

            // 监听发布文章按钮点击事件
            util.on('lay-on', {
                'test-page-custom': () => {
                    // 判断是否输入了文章标题
                    let title = form.val('filter-test-layer').title
                    if (title.trim() === '') {
                        layer.msg('请输入文章标题', {icon: 7, time: 1500, anim: 6});
                        return;
                    }
                    layer.open({
                        type: 1,
                        area: ['600px', 'auto'],
                        resize: false,
                        shadeClose: true,
                        title: '发布文章',
                        offset: 'auto',
                        content: $('#post-template').html(),
                        success: function () {
                            // 对弹层中的表单进行初始化渲染
                            form.render();
                            form.on('submit(publish)', function (data) {
                                let tags = data.field;
                                let category = form.val('filter-test-layer').category || "{{ category_list[0].id }}";
                                let html = editor.getHTML()
                                let markdown = editor.getMarkdown()
                                let form_data = {
                                    title: title,
                                    category: category,
                                    tags: JSON.stringify(tags),
                                    html: html,
                                    markdown: markdown,
                                    img_list: JSON.stringify(img_list)
                                }
                                $.post('{{ url_for('admin.add_article') }}', form_data, (res) => {
                                        if (res === 'success') {
                                            layer.close(1, () => {
                                                layer.msg('保存成功', {icon: 1, time: 1500}, () => {
                                                    window.location.href = '{{ url_for("admin.article") }}'
                                                })
                                            })
                                        }
                                    }
                                )
                                return false; // 阻止默认 form 跳转
                            });
                        }
                    })
                }
            })
            // 监听保存草稿按钮点击事件
            form.on('submit(saveDraft)', function (data) {
                var field = data.field; // 获取表单全部字段值
                // 此处可执行 Ajax 等操作
                // …
                return false; // 阻止默认 form 跳转
            });
        });
    </script>
{% endblock %}